package com.smartsoft.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.smartsoft.R;
import com.smartsoft.model.CountryItem;
import java.util.List;

/**
 * Adapter for countries carousel ListView.
 */
public class CountriesAdapter extends BaseAdapter {

    /**
     * For debug purposes.
     */
    private static final String TAG = BaseAdapter.class.getName();
    public static final int CAROUSEL_MAX_POSITION = Integer.MAX_VALUE;
    public static final int CAROUSEL_MIDDLE_POSITION = CAROUSEL_MAX_POSITION / 2;

    private List<CountryItem> countryItems;
    private Context context;

    public CountriesAdapter(List<CountryItem> countryItems, Context context) {
        this.context = context;
        this.countryItems = countryItems;
    }

    @Override
    public int getCount() {
        return CAROUSEL_MAX_POSITION;
    }

    @Override
    public CountryItem getItem(int position) {
        int relativePosition = position % countryItems.size();
        Log.d(TAG, "Relative position in country collection is " + relativePosition);
        return countryItems.get(relativePosition);
    }

    @Override
    public long getItemId(int position) {
        return CAROUSEL_MAX_POSITION;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Log.d(TAG, "getView() method called at position " + position);
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.country_view_item, parent, false);
            convertView.setTag(new ViewHolder(
                    (ImageView) convertView.findViewById(R.id.country_flag_image),
                    (TextView) convertView.findViewById(R.id.country_name)
            ));
        }

        CountryItem countryItem = getItem(position);
        ViewHolder viewHolder = (ViewHolder) convertView.getTag();
        // Setup country's flag image and name.
        viewHolder.countryName.setText(countryItem.getCountryName());
        viewHolder.countryFlag.setImageResource(countryItem.getCountryFlagResId());
        return convertView;
    }

    /**
     * Holder for the fragment's inner views.
     * Increases speed of finding those views.
     */
    private static final class ViewHolder {
        public final ImageView countryFlag;
        public final TextView countryName;

        private ViewHolder(ImageView countryFlag, TextView countryName) {
            this.countryFlag = countryFlag;
            this.countryName = countryName;
        }
    }

}
